<?php

namespace app\api\controller;



/**
 * 文件库管理
 * Class Upload
 * @package app\api\controller
 */
class Images extends Controller
{
    private $config;
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function initialize()
    {
        parent::initialize();
        // 存储配置信息
        //$this->config = SettingModel::getItem('storage');
        // 验证用户
        $this->user = $this->getUser();
    }

    public  function addImages()
    {
        if (empty($_FILES)) {
            return json(['code' => 1003, 'msg' => '图片为空', 'data' =>'']);
        }
        if(!empty($_FILES["name"]["name"])) {//检测表单传递文件数据
            $fileinfo = $_FILES["name"];
            if ($fileinfo['size'] < 10000000 && $fileinfo['size'] > 0) {//大小筛选
                if ($fileinfo['type'] == 'image/jpeg' || 'image/jpg' || 'image/png' || 'image/gif') {//类型筛选
                    if (!file_exists("./uploads")) {
                        mkdir("./uploads");
                    }
                    $path = time().rand ('1','99');
                    move_uploaded_file($fileinfo['tmp_name'], "uploads/" . $path.'.jpg') or die("文件上传失败");
                    $this->makezoom("uploads/" . $path.'.jpg', 200, 100, 'uploads/200_100/');
                    //$this->makezoom("uploads/" . $fileinfo['name'], 1920, 900, 'uploads/1920_900/');
                    return json(['code' => 1000, 'msg' => '图片上传成功', 'data' => $path]);
                } else {
                    return json(['code' => 1001, 'msg' => '请上传正确格式的图片', 'data' =>'']);
                }

            } else {
                return json(['code' => 1002, 'msg' => '图片过大或者未知', 'data' =>'']);
            }
        }
    }
        public function  makezoom($src='',$width=200,$height=200,$dir = 'uploads/200_200/',$delsrc=false)//产生缩略图函数
        {
            if(!file_exists($dir)){
                mkdir($dir);
            }
            $srcInfo = getimagesize($src);//获取图片信息数组
            $srcType = image_type_to_extension($srcInfo[2], false);//获取图片类型
            $fun = 'imagecreatefrom' . $srcType;//由图片文件创建图像资源
            $srcImage = $fun($src);
            //创建缩略图资源
            //$scale = $srcInfo[0] / $srcInfo[1];
            //$height = $width / $scale;
            $zoomImg = imagecreatetruecolor($width, $height);
            //图像资源放到缩略图资源上
            imagecopyresampled($zoomImg, $srcImage, 0, 0, 0, 0, $width, $height, $srcInfo[0], $srcInfo[1]);
            //输出缩略图资源

            $output = 'image' . $srcType;
            $output($zoomImg, $dir. basename($src));
            //销毁资源

            imagedestroy($srcImage);
            imagedestroy($zoomImg);
            //删除原图
            if($delsrc){
                unlink($src);
            }
        }




}